<template>
  <Dialog v-model="show" @confirm="handleSubmit" :title="$t('sellerManage.resetPswDia.重置密码')" width="500">
    <el-form :model="formData" label-width="100px" ref="formRef" :rules="rules">
      <el-form-item :label="$t('sellerManage.resetPswDia.登录密码')" prop="newPass">
        <el-input
          type="password"
          v-model="formData.newPass"
          :placeholder="$t('sellerManage.resetPswDia.请设置6到20位登录密码')"
        />
      </el-form-item>
      <el-form-item :label="$t('sellerManage.resetPswDia.确认密码')" prop="confirmPassword">
        <el-input
          type="password"
          v-model="formData.confirmPassword"
          :placeholder="$t('sellerManage.resetPswDia.确认密码需要与登录密码一致')"
        />
      </el-form-item>
    </el-form>
  </Dialog>
</template>
<script setup>
import { ref } from "vue";
import Dialog from "@/components/dialog.vue";
import Api from "@/config/api/api";
import { ElMessage } from "element-plus";
import Tools from "@/utils/tools";
import { useI18n } from "vue-i18n";

const { t: $t } = useI18n();

const show = defineModel();
const props = defineProps({
  data: {
    type: Object,
    default: () => ({}),
  },
});

const formData = ref({
  newPass: "",
  confirmPassword: "",
});

const validatePass1 = (rule, value, callback) => {
  if (value === "") {
    callback(new Error($t('sellerManage.resetPswDia.请输入密码')));
  } else if (value.length < 6 || value.length > 20) {
    callback(new Error($t('sellerManage.resetPswDia.密码长度应在6到20位之间')));
  } else {
    if (formData.value.confirmPassword !== "") {
      formRef.value.validateField("confirmPassword");
    }
    callback();
  }
};

const validatePass2 = (rule, value, callback) => {
  if (value === "") {
    callback(new Error($t('sellerManage.resetPswDia.请输入确认密码')));
  } else if (value.length < 6 || value.length > 20) {
    callback(new Error($t('sellerManage.resetPswDia.密码长度应在6到20位之间')));
  } else if (value !== formData.value.newPass) {
    callback(new Error($t('sellerManage.resetPswDia.两次输入密码不一致')));
  } else {
    callback();
  }
};

const rules = ref({
  newPass: [{ required: true, validator: validatePass1, trigger: "blur" }],
  confirmPassword: [
    { required: true, validator: validatePass2, trigger: "blur" },
  ],
});

const formRef = ref();

const handleSubmit = () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      Api.tenantResetPass({
        id: props.data.id,
        password: Tools.rsaEncrypt(formData.value.newPass),
      }).then((res) => {
        if (res.status === 200) {
          ElMessage.success($t('sellerManage.resetPswDia.密码重置成功'));
          close();
        }
      });
    }
  });
};

const close = () => {
  formData.value = {
    newPass: "",
    confirmPassword: "",
  };
  show.value = false;
};
</script>
